const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const cors = require('cors')
const USER_LIMITS = 3;

const app = express();
const httpServer = http.createServer(app);
const io = new Server(httpServer);
const path = require('path')
const getRoomUsers = room => {
  const myRoom = io.sockets.adapter.rooms[room];
  console.log('123',myRoom);
  return myRoom || [];
};

const getRoomUsersCount = room => {
  return getRoomUsers(room).length;
};
// console.log(express.static);
app.use('/index', express.static('./view/'))

// app.all('*', function (req, res, next) {
//   res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:5500/');//仅支持配置一个域名
//   res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
//   res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
//   res.header('Access-Control-Allow-Credentials', true)//允许客户端携带验证信息
//   next();
// });

// app.use(cors({
//   origin: ['http://127.0.0.1:5500/', 'http://www.baidu.com'],//可设置多个跨域域名
//   credentials: true//允许客户端携带验证信息
// }))
// 连接事件
io.sockets.on('connection', socket => {
  console.log('创建链接');
  // 转发消息
  socket.on('message', (room, data) => {
    console.log(`message, room: ${room}, data type: ${data.type}`);
    socket.to(room).emit('message', room, data);
  });

  // 加入房间
  socket.on('join', room => {
    socket.join(room);
    const userCount = getRoomUsersCount(room);
    console.log(`user join, room number ${userCount}`);

    // 房间未满员
    if (userCount < USER_LIMITS) {
      console.log('房间未满员',userCount < USER_LIMITS);
      // 广播用户加入房间
      socket.emit('joined', room, socket.id);
      console.log('用户加入房间',room, socket.id);
      if (userCount >= 1) {
        console.log('其他用户加入房间');
        // 广播其他用户加入房间
        socket.to(room).emit('otherJoin', room, socket.id);
      }
    }
    // 房间满员
    else {
      console.log('房间满员');
      socket.leave(room);
      socket.emit('full', room, socket.id);
    }
  });

  socket.on('leave', room => {
    socket.leave(room);

    const userCount = getRoomUsersCount(room);
    console.log(`user leave, room number ${userCount}`);

    // 广播有用户退出房间
    socket.to(room).emit('exit', room, socket.id);

    socket.emit('leaved', room, socket.id);
  });
});

httpServer.listen(3100, (data) => {
  console.log(data);
  console.log('3100的端口服务启动成功！');
});

